using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using RevitForge.Services;
using System;
using System.IO;
using System.Reflection;

namespace RevitForge.Commands
{
    [Transaction(TransactionMode.Manual)]
    public class ScriptBotCommand : IExternalCommand
    {
        private static ExternalEvent _scriptExecuteEvent;
        private static ScriptExecuteHandler _scriptExecuteHandler;

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document doc = uiapp.ActiveUIDocument.Document;
            // 首次运行时初始化
            if (!DockablePane.PaneIsRegistered(ScriptBotDockablePaneProvider.PaneId))
            {
                _scriptExecuteHandler = new ScriptExecuteHandler(commandData, message, elements);
                _scriptExecuteEvent = ExternalEvent.Create(_scriptExecuteHandler);
                var provider = new ScriptBotDockablePaneProvider(_scriptExecuteEvent);
                commandData.Application.RegisterDockablePane(
                    ScriptBotDockablePaneProvider.PaneId,
                    "ScriptBot",
                    provider);
                try
                {
                    // 获取当前程序集所在目录
                    string assemblyPath = Assembly.GetExecutingAssembly().Location;
                    string assemblyDir = Path.GetDirectoryName(assemblyPath);
                    // 拼接文件路径
                    string filePath = Path.Combine(assemblyDir, "Source", "Simple.rfa");
                    // 使用OpenAndActivateDocument方法打开文档
                    UIDocument openedUiDoc = uiapp.OpenAndActivateDocument(filePath);
                    Document openedDoc = openedUiDoc.Document;
                    // 确保当前文档不是活动文档
                    if (doc != null)
                    {
                        // 获取原始文档的路径
                        string originalDocPath = doc.PathName;
                        if (!string.IsNullOrEmpty(originalDocPath))
                        {
                            // 将原始文档设置为活动文档
                            uiapp.OpenAndActivateDocument(originalDocPath);
                        }
                    }
                    // 关闭已经变为非活动状态的文档
                    openedDoc.Close(false);
                }
                catch (Exception ex)
                {
                    TaskDialog.Show("Error", ex.Message);
                }
                ScriptBotDockablePaneProvider.ShowPane(commandData.Application);
            }
            // 切换窗口显示状态
            ScriptBotDockablePaneProvider.ShowPane(commandData.Application);
            return Result.Succeeded;
        }
    }
}